package permission

import (
	"context"
	"gf-vben-admin/internal/model/system/entity"
	service "gf-vben-admin/internal/service/system"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
)

// InitPermission 初始化系统API接口
func InitPermission(ctx context.Context) {
	api := g.Server().GetOpenApi()
	permissions := make([]entity.Permission, 0)
	now := gtime.Now()
	for key, path := range api.Paths {
		json := gjson.New(path)
		strAny := json.MapStrAny()
		for k, v := range strAny {
			if k != "summary" {
				permissions = append(permissions, entity.Permission{
					TenantCode:  "gf-vben",
					Code:        gstr.Replace(gstr.TrimLeft(key, "/"), "/", ".") + "." + k,
					Path:        key,
					Tag:         gconv.SliceStr(gconv.Map(v)["tags"])[0],
					Description: gjson.New(v).Get("summary").String(),
					Method:      k,
					CreateDate:  now,
					Creator:     "admin",
					CreatorId:   "1",
				})
			}
		}
	}
	err := service.Permission().InitPermission(ctx, permissions)
	if err != nil {
		print(any(err))
	}
	g.Log().Info(ctx, "初始化API完成")

}
